package com.hae.shop.micoshopportalweb.controller.member;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.Constants;
import com.hae.shop.common.util.BeanConvertUtil;
import com.hae.shop.common.util.OtherUtils;
import com.hae.shop.member.model.reqDto.UserLoginReqDto;
import com.hae.shop.member.model.respDto.UserLoginRespDto;
import com.hae.shop.micoshopportalweb.controller.member.feign.MemberFeign;
import com.hae.shop.micoshopportalweb.controller.member.vo.LoginReqVo;
import com.hae.shop.micoshopportalweb.utils.CookieUtils;
import com.hae.shop.micoshopportalweb.utils.RandomValidateCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * 登录相关
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    private MemberFeign memberFeign;

    /**
     * 跳转到注册页面
     *
     * @return
     */
    @GetMapping("/login.html")
    public String getLogin() {
        return Constants.MEMBER_LOGIN_PAGE;
    }

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    public String postLogin(@ModelAttribute("loginReqVo") @Valid LoginReqVo loginReqVo, HttpSession httpSession,
                            HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult, Model model) {
        // 1.参数验证
        if (bindingResult.hasErrors()) {
            // 获取第一个错误!
            model.addAttribute("error",bindingResult.getFieldError().getDefaultMessage());
            return Constants.MEMBER_LOGIN_PAGE;
        }

        // 2.校对验证码
        if (!RandomValidateCodeUtil.checkVerify(loginReqVo.getGraphicCode(), httpSession)) {
            model.addAttribute("error", "图形验证码错误");
            return Constants.MEMBER_LOGIN_PAGE;
        }

        // 3.设置登录类型和设备信息
        UserLoginReqDto userLoginReqDto = BeanConvertUtil.EToT(loginReqVo, UserLoginReqDto.class);
        userLoginReqDto.setLoginType("PC");
        userLoginReqDto.setDeviceInfor(OtherUtils.webBrowserInfo(request));

        // 4.调用登录程序
        try {
            //不成功则返回错误
            Response<UserLoginRespDto> userLoginRespDtoResponse = memberFeign.login(userLoginReqDto);
            if (null == userLoginRespDtoResponse.getResult()) {
                model.addAttribute("error", userLoginRespDtoResponse.getErrorMsg());
                return Constants.MEMBER_LOGIN_PAGE;
            }
            //成功则将userid放入页面，且将token放入coocike
            model.addAttribute("member_id", userLoginRespDtoResponse.getResult().getUserid());
            CookieUtils.setCookie(request, response, "mico_token", userLoginRespDtoResponse.getResult().getToken());
            return Constants.INDEX_FTL; //REDIRECT_INDEX 省去跳转
        } catch (Exception e) {
            model.addAttribute("error", "系统出现错误!");
            return Constants.MEMBER_LOGIN_PAGE;
        }
    }

    /**
     *
     * 退出登录
     * @return
     */
    @RequestMapping("/exit")
    public String exit(HttpServletRequest request, Model model) {
        // 1.获取浏览器token
        String token = CookieUtils.getCookieValue(request, "mico_token");
        if (!StringUtils.isEmpty(token)) {
            // 2.token不空时，调用member服务删除token相关记录
            Response<Boolean> loginoutResponse = null;
            try {
                loginoutResponse = memberFeign.loginout(token);
            } catch (Exception e) {
                log.error("系统出现错误", e);
                return Constants.ERROR_FTL;
            }
            if (!loginoutResponse.getResult()) {
                // 删除不成功则返回错误页面
                return Constants.ERROR_FTL;
            }
            //成功则将userid放入页面，且将token放入coocike
//            model.addAttribute("member_id", userLoginRespDtoResponse.getResult().getUserid());
//            CookieUtils.setCookie(request, response, "mico_token", userLoginRespDtoResponse.getResult().getToken());
        }
        return Constants.INDEX_FTL;
    }

}
